/**
 * Title: FileTransferManager.java
 * Description:
 * Copyright: Copyright (c) 2008
 * Company:深圳彩讯科技有限公司
 * Author 罗旭东 (hi@luoxudong.com)
 * Date 2013-8-14 下午5:33:04
 * Version 1.0 
 */
package com.luoxudong.phonenumber.service.net.http.filetransfer.manager;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.content.Context;

import com.luoxudong.phonenumber.service.exception.PhoneNumberExceptionCode;
import com.luoxudong.phonenumber.service.net.http.asynchttp.DownloadHttpResponseHandler;
import com.luoxudong.phonenumber.service.net.http.asynchttp.DownloadRequestParams;
import com.luoxudong.phonenumber.service.net.http.asynchttp.UploadHttpResponseHandler;
import com.luoxudong.phonenumber.service.net.http.asynchttp.UploadRequestParams;
import com.luoxudong.phonenumber.service.net.http.filetransfer.interfaces.IDownloadListener;
import com.luoxudong.phonenumber.service.net.http.filetransfer.interfaces.IFileTransferManager;
import com.luoxudong.phonenumber.service.net.http.filetransfer.interfaces.IRemoveDownloadListener;
import com.luoxudong.phonenumber.service.net.http.filetransfer.interfaces.IRemoveUploadListener;
import com.luoxudong.phonenumber.service.net.http.filetransfer.interfaces.IStopDownloadListener;
import com.luoxudong.phonenumber.service.net.http.filetransfer.interfaces.IStopUploadListener;
import com.luoxudong.phonenumber.service.net.http.filetransfer.interfaces.IUploadListener;
import com.luoxudong.phonenumber.service.net.http.filetransfer.vo.RequestHolder;
import com.luoxudong.phonenumber.service.net.http.filetransfer.vo.TransferStatus;
import com.luoxudong.phonenumber.service.net.http.filetransfer.vo.TransferType;
import com.luoxudong.phonenumber.service.utils.EvtLog;

/** 
 * ClassName: FileTransferManager 
 * Description:文件管理类
 * Create by 罗旭东
 * Date 2013-8-14 下午5:33:04 
 */ 
public class FileTransferManager implements IFileTransferManager{
	private static final String TAG = FileTransferManager.class.getSimpleName();
	
	/**
	 * 全局传输ID
	 */
	private int transferId = 0;
	
	private Object syncObj = new Object();
	
	/**
	 * 下载监听器集合
	 */
	private List<IDownloadListener> downloadListeners = null;
	
	/**
	 * 上传监听器集合
	 */
	private List<IUploadListener> uploadListeners = null;
	
	public FileTransferManager() {
		// 下载监听列表
		downloadListeners = Collections.synchronizedList(new ArrayList<IDownloadListener>());
		// 上传监听列表
		uploadListeners = Collections.synchronizedList(new ArrayList<IUploadListener>());
	}
	
	@Override
	public int download(Context context, String url, String localFileDir, String fileName) {
		return download(context, url, localFileDir, fileName, fileName);
	}

	@Override
	public int download(Context context, String url, String localFileDir, String fileName, String displayName) {
		int downloadId = -1;
		
		synchronized (syncObj) {
			downloadId = transferId++;
		}
		
		//当前任务不在下载则加入下载队列
		if (!isDownloading(downloadId))
		{
			DownloadHttpResponseHandler handler = new DownloadHttpResponseHandler(downloadId, downloadListeners);
			
			//下载服务所需要的参数
			DownloadRequestParams downloadRequestParams = new DownloadRequestParams();
			downloadRequestParams.setResponseHandler(handler);
			
			//传输管理通用参数设置
			RequestHolder requestHolder = new RequestHolder();
			requestHolder.setUrl(url);
			requestHolder.setDownloadParams(downloadRequestParams);
			
			FileTransferTask fileTransferTask = new FileTransferTask();
			fileTransferTask.setContext(context);
			fileTransferTask.setRequestHolder(requestHolder);
			fileTransferTask.setTransferId(downloadId);
			fileTransferTask.setTransferStatus(TransferStatus.ready.getValue());
			fileTransferTask.setTransferType(TransferType.download.getValue());
			DownloadManager.addDownloadTask(fileTransferTask);//加入下载队列中
		}
		
		return downloadId;
	}

	@Override
	public void stopDownload(int downloadId, IStopDownloadListener stopDownloadListener) {
		FileTransferTask downloadTask = DownloadManager.findDownloadTask(downloadId);
		
		if (downloadTask != null)
		{
			downloadTask.cancel();
		
			if (stopDownloadListener != null)
			{
				//该任务已经停止下载
				stopDownloadListener.onStopDownloadSuccess(downloadId);
			}
			
		}
		else//下载任务不存在，已经完成或被取消
		{
			if (stopDownloadListener != null)
			{
				//该任务已经停止下载
				stopDownloadListener.onStopDownloaded(downloadId);
			}
		}
	}

	@Override
	public void removeDownload(int downloadId, final IRemoveDownloadListener removeDownloadListener) {
		if (isDownloading(downloadId))//当前正在下载
		{
			//先停止下载
			stopDownload(downloadId, new IStopDownloadListener() {
				
				@Override
				public void onStopDownloaded(int downloadId) {
					
					if (removeDownloadListener != null)
					{
						removeDownloadListener.onRemoveSuccess(downloadId);
					}
				}
				
				@Override
				public void onStopDownloadSuccess(int downloadId) {
					
					if (removeDownloadListener != null)
					{
						removeDownloadListener.onRemoveSuccess(downloadId);
					}
				}
				
				@Override
				public void onStopDownloadFail(int downloadId) {
					if (removeDownloadListener != null)
					{
						EvtLog.e(TAG, "停止下载失败!");
						removeDownloadListener.onRemoveFail(downloadId, "停止下载失败!");
					}
				}
			});
		}
		else//下载已经停止
		{
			
			if (removeDownloadListener != null)
			{
				removeDownloadListener.onRemoveSuccess(downloadId);
			}
		}
	}

	@Override
	public void addDownloadListener(IDownloadListener downloadListener) {
		synchronized (downloadListeners) {
			if (!downloadListeners.contains(downloadListener))
			{
				downloadListeners.add(downloadListener);
			}
		}
	}

	@Override
	public void removeDownloadListener(IDownloadListener downloadListener) {
		synchronized (downloadListeners) {
			downloadListeners.remove(downloadListener);
		}
	}

	@Override
	public int upload(Context context, String url, String localFileDir,String fileName) {
		EvtLog.e(TAG, "上传------");
		int uploadId = -1;
		
		// 判断本地文件是否存在
		File file = new File(localFileDir, fileName);

		if (!file.exists()) {
			if (uploadListeners != null) {
				for (IUploadListener uploadListener : uploadListeners) {
					uploadListener.onUploadFail(uploadId, PhoneNumberExceptionCode.defaultExceptionCode.getErrorCode(), "本地文件不存在!");
				}
			}
			EvtLog.e(TAG, "本地文件不存在!");
			return -1;
		}

		synchronized (syncObj) {
			uploadId = transferId++;
		}
		
		if (!isUploading(uploadId))
		{
			EvtLog.e(TAG, "上传" + uploadId);
			UploadHttpResponseHandler handler = new UploadHttpResponseHandler(uploadId, uploadListeners);
			
			//下载服务所需要的参数
			UploadRequestParams uploadRequestParams = new UploadRequestParams();
			uploadRequestParams.setFilePath(file.getAbsolutePath());
			uploadRequestParams.setResponseHandler(handler);
			
			//传输管理通用参数设置
			RequestHolder requestHolder = new RequestHolder();
			requestHolder.setUrl(url);
			requestHolder.setUploadParams(uploadRequestParams);
			
			FileTransferTask fileTransferTask = new FileTransferTask();
			fileTransferTask.setContext(context);
			fileTransferTask.setRequestHolder(requestHolder);
			fileTransferTask.setTransferId(uploadId);
			fileTransferTask.setTransferStatus(TransferStatus.ready.getValue());
			fileTransferTask.setTransferType(TransferType.upload.getValue());
			UploadManager.addUploadTask(fileTransferTask);//加入上传队列中
		}

		return uploadId;
	}

	@Override
	public void stopUpload(int uploadId, IStopUploadListener stopUploadListener) {
		FileTransferTask uploadTask = UploadManager.findUpnloadTask(uploadId);
		
		if (uploadTask != null)
		{
			uploadTask.cancel();
			if (stopUploadListener != null)
			{
				stopUploadListener.onStopUploadSuccess(uploadId);
			}
		}
		else//下载任务不存在，已经完成或被取消
		{
			if (stopUploadListener != null)
			{
				//该任务已经停止下载
				stopUploadListener.onStopUploaded(uploadId);
			}
		}
	}

	@Override
	public void removeUpload(final int uploadId, final IRemoveUploadListener removeUploadListener) {
		if (isUploading(uploadId))//当前正在上传
		{
			//先停止上传
			stopUpload(uploadId, new IStopUploadListener() {
				
				@Override
				public void onStopUploaded(int uploadId) {
					
					if (removeUploadListener != null)
					{
						removeUploadListener.onRemoveUploadSuccess(uploadId);
					}
				}
				
				@Override
				public void onStopUploadSuccess(int uploadId) {
					
					if (removeUploadListener != null)
					{
						removeUploadListener.onRemoveUploadSuccess(uploadId);
					}
				}
				
				@Override
				public void onStopUploadFail(int uploadId, String msg) {
					if (removeUploadListener != null)
					{
						EvtLog.e(TAG, "删除上传记录失败!");
						removeUploadListener.onRemoveUploadFail(uploadId, "删除上传记录失败!");
					}
				}
			});
		}
		else//下载已经停止
		{
			if (removeUploadListener != null)
			{
				removeUploadListener.onRemoveUploadSuccess(uploadId);
			}
		}
	}

	@Override
	public void addUploadListener(IUploadListener uploadListener) {
		synchronized (uploadListeners) {
			if (!uploadListeners.contains(uploadListener))
			{
				uploadListeners.add(uploadListener);
			}
		}
	}

	@Override
	public void removeUploadListener(IUploadListener uploadListener) {
		synchronized (uploadListeners) {
			uploadListeners.remove(uploadListener);
		}
	}
	
	@Override
	public void stopAllTransferTask() {
		DownloadManager.stopAllDownloadTask();
		UploadManager.stopAllUploadTask();
	}
	
	/**
	 * 是否正在下载
	 * @return
	 * @return boolean
	 */
	private boolean isDownloading(int downloadId)
	{
		return DownloadManager.isDownloading(downloadId);
	}
	
	/**
	 * 是否正在上传
	 * @param uploadId
	 */
	private boolean isUploading(int uploadId)
	{
		return UploadManager.isUploading(uploadId);
	}
	
}
